package com.example.viewpager_demo;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lian on 2016/5/9.
 */
public class AutoScrollViewPager extends ViewPager
{
    Timer mTimer;
    private Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            //滚动到下一张图片
            setCurrentItem(getCurrentItem()+1);
        }
    };
    public AutoScrollViewPager(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    public void setAdapter(PagerAdapter adapter)
    {
        super.setAdapter(adapter);
        setCurrentItem(((AutoScrollPagerAdapter)adapter).getItemCount()*1000);
    }

    //自动滑动
    public void startSlinding()
    {
        mTimer = new Timer();
        mTimer.schedule(new TimerTask()
        {
            @Override
            public void run()
            {
                mHandler.sendEmptyMessage(0);
            }
        },3000,2000);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev)
    {
        switch (ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                stopSlinding();
                break;
            case MotionEvent.ACTION_UP:
                startSlinding();
                break;
        }
        return super.onTouchEvent(ev);
    }

    //停止滚动
    public void stopSlinding()
    {
        if(mTimer!=null)
        {
            mTimer.cancel();
            mTimer = null;
        }
    }
}
